<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<!-- <a-breadcrumb separator=">" class="mb-4 pl-[10px]">
			<a-breadcrumb-item>合同管理</a-breadcrumb-item>
			<a-breadcrumb-item><a href="">合同管理</a></a-breadcrumb-item>
		</a-breadcrumb> -->
		<div class="flex justify-between items-end">
			<a-space :size="16" class="flex-wrap">
				<a-input-group compact>
					<a-select v-model:value="searchType" style="width: 150px" @change="searchText = ''">
						<a-select-option :value="0">客户名称</a-select-option>
						<a-select-option :value="1">联系号码</a-select-option>
					</a-select>
					<a-input
						v-model:value="searchText"
						style="width: 200px"
						placeholder="请输入关键字搜索"
						@pressEnter="table.clearRefreshSelected(true)"
					></a-input>
				</a-input-group>
				<a-input-group compact>
					<span class="mt-[4px]">职能范围：</span>
					<a-select
						placeholder="请选择查询范围"
						v-model:value="searchOption.data"
						class="w-[200px]"
						@change="dataChange"
					>
						<a-select-option v-if="store.roleAuthMap.self" value="1">本人</a-select-option>
						<a-select-option v-if="store.roleAuthMap.dept" value="2">本部门</a-select-option>
						<a-select-option v-if="store.roleAuthMap.deptAndSub" value="3">本部门及下级部门</a-select-option>
						<a-select-option v-if="store.roleAuthMap.all" value="4">全企业</a-select-option>
						<a-select-option v-if="store.roleAuthMap.dept" value="5" @click="onCustomClick">自定义</a-select-option>
					</a-select>
					<a-tree-select
						v-if="searchOption.data === '5'"
						v-model:value="searchOption.tempPersonIds"
						style="width: 360px"
						:tree-data="orgUserTreeData"
						tree-checkable
						allow-clear
						:show-checked-strategy="SHOW_PARENT"
						placeholder="请选择人员范围"
						tree-node-filter-prop="label"
						:fieldNames="fieldNames"
						max-tag-count="responsive"
						:dropdownMatchSelectWidth="false"
						treeNodeFilterProp="name"
						@change="onPersonChange"
					/>
				</a-input-group>
				<a-button type="primary" @click="table.refresh(true)">查询</a-button>
				<a-button @click="screenVisible = true">更多筛选</a-button>
			</a-space>
			<a-button v-if="hasPerm('bizContractSwitchExport')" :loading="loading" type="primary" @click="onExportContract"
				>导出</a-button
			>
		</div>
	</a-card>
	<!-- 表格展示区域 -->
	<!--	class="h-full"-->
	<a-card :bordered="false">
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ column, record, index }">
				<template v-if="column.dataIndex === 'sound'">
					<a-space v-if="record.sound && record.recordFlagStaus === '已接通'" align="center">
						<el-popover
							:visible="visible[record.id]"
							placement="right"
							:width="400"
							trigger="click"
							@hide="onPlayPopoverHide(record.id)"
						>
							<template #reference>
								<svg-icon
									name="audio"
									:class="`audio ${musicData.index === index && 'active'}`"
									@click="onRadioPlay(record, index)"
								/>
							</template>
							<div class="flex flex-col items-center py-2">
								<div class="w-[100%] flex justify-between items-center px-2 pb-4">
									<span>通话录音</span>
									<el-icon :size="20">
										<el-icon-Close class="cursor-pointer" @click="onPlayPopoverClose(record.id)" />
									</el-icon>
								</div>
								<audio :ref="(el) => setAudioNodeList(el, record.id)" controls controlslist="nodownload noplaybackrate">
									<source :src="musicData.url" type="audio/ogg" />
									<source :src="musicData.url" type="audio/mpeg" />
									<source :src="musicData.url" type="audio/wav" />
								</audio>
								<div class="mt-2 p-2 cursor-pointer" @click="onRadioDownload(record)">
									<download-outlined style="margin-right: 8px; font-size: 18px" />
									<span>下载</span>
								</div>
								<div class="p-2">
									<span style="margin: 0 12px">播速：</span>
									<el-select
										v-model="speed"
										placeholder="Select"
										size="small"
										style="width: 60px"
										@change="onPlaySpeedChange"
									>
										<el-option v-for="item in speedOptions" :key="item.value" :label="item.label" :value="item.value" />
									</el-select>
								</div>
							</div>
						</el-popover>
						<download-outlined style="font-size: 22px; cursor: pointer" @click="onRadioDownload(record)" />
					</a-space>
					<span v-else>-</span>
				</template>
				<!-- <template v-if="column.dataIndex === 'action'">
					<a-popover placement="left">
						<template #content>
							<div class="flex flex-col">
								<a-button
									v-if="hasPerm('bizContractSwitchView')"
									type="link"
									@click="$router.push(`/biz/contractSwitch/detail/${record.id}`)"
								>
									查看详情
								</a-button>
							</div>
						</template>
						<a>操作</a>
					</a-popover>
				</template> -->
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal
		v-model:visible="screenVisible"
		title="更多筛选"
		:footer="null"
		:closable="false"
		:width="500"
		@cancel="cancelMoreSearch"
	>
		<a-form :label-col="labelCol">
			<a-form-item label="通话状态">
				<a-select v-model:value="moreSearch.recordFlag" allowClear placeholder="请选择">
					<a-select-option value="">全部</a-select-option>
					<a-select-option value="1">已接通</a-select-option>
					<a-select-option value="0">未接通</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="通讯方式">
				<a-select v-model:value="moreSearch.communicationType" allowClear placeholder="请选择">
					<a-select-option value="">全部</a-select-option>
					<a-select-option value="1">4G多卡话机</a-select-option>
					<a-select-option value="0">线路外呼</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="通话时间">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.transTime"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
			<a-form-item label="通话时长">
				<a-input-number
					v-model:value="moreSearch.callMinNum"
					:min="0"
					placeholder="请输入（秒）"
					controls-position="right"
					class="w-[150px]"
				></a-input-number>
				<span style="padding: 0 22px">-</span>
				<a-input-number
					v-model:value="moreSearch.callMaxNum"
					:min="1"
					placeholder="请输入（秒）"
					controls-position="right"
					class="w-[150px]"
				></a-input-number>
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="clearSearch">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="doMoreSearch">筛选</a-button>
				<a-button @click="cancelMoreSearch">取消</a-button>
			</a-space>
		</div>
	</a-modal>

	<!--	<audio ref="audioNode" :v-show="false" loop>-->
	<!--		<source :src="musicData.url" type="audio/ogg" />-->
	<!--		<source :src="musicData.url" type="audio/mpeg" />-->
	<!--		<source :src="musicData.url" type="audio/wav" />-->
	<!--	</audio>-->
</template>
<script setup>
	import { message, TreeSelect } from 'ant-design-vue'
	import tool from '@/utils/tool'

	import callRecordApi from '@/api/biz/bizCallRecordApi'
	import downloadUtil from '@/utils/downloadUtil'
	import { globalStore } from '@/store'

	const store = globalStore()

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onBeforeMount(() => {})
	const columns = [
		{
			title: '通讯方式',
			dataIndex: 'communicationTypeName',
			align: 'center',
			width: 120
			// fixed: 'left'
		},
		{
			title: '呼入/呼出',
			dataIndex: 'callTypeName',
			align: 'center',
			width: 100
		},
		{
			title: '通话时间',
			dataIndex: 'fromStartTime',
			align: 'center',
			ellipsis: true,
			width: 160,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '员工姓名',
			dataIndex: 'employeeName',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '员工号码',
			dataIndex: 'bingPhone',
			width: 120,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '关联客户',
			dataIndex: 'customerName',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '关联联系人',
			dataIndex: 'contactPerson',
			width: 120,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '联系号码',
			dataIndex: 'contactPhone',
			width: 120,
			align: 'center',
			customRender: ({ text }) => text || '-'
		},
		{
			title: '通话状态',
			dataIndex: 'recordFlagStaus',
			width: 120,
			align: 'center'
		},
		{
			title: '通话时长（秒）',
			dataIndex: 'bduration',
			width: 120,
			align: 'center'
		},
		{
			title: '录音',
			dataIndex: 'sound',
			width: 80,
			align: 'center'
		}
	]
	// columns.push({
	// 	title: '操作',
	// 	dataIndex: 'action',
	// 	align: 'center',
	// 	fixed: 'right',
	// 	width: '100px'
	// })

	/**
	 * 录音
	 */
	const musicData = ref({
		id: null,
		index: null,
		url: null
	})
	const audioNodeList = ref({})
	const setAudioNodeList = (el, id) => {
		audioNodeList.value[`audioNode-${id}`] = el
	}
	const onRadioPlay = (scope, index) => {
		const audioNode = audioNodeList.value[`audioNode-${scope.id}`]
		if (index === musicData.value.index) {
			nextTick(() => {
				if (audioNode.paused) {
					// audioNode.value.play()
				} else {
					// audioNode.value.pause()
					musicData.value = {
						id: null,
						index: ''
					}
				}
				visible.value[scope.id] = !visible.value[scope.id]
			})
		} else {
			visible.value[musicData.value.id] = false
			const preAudioNode = audioNodeList.value[`audioNode-${musicData.value.id}`]
			preAudioNode && !preAudioNode?.paused && preAudioNode.pause()
			musicData.value = { id: scope.id, url: scope.sound, index: index }
			audioNode.load()
			nextTick(() => {
				// audioNode.value.play()
				visible.value[scope.id] = true
			})
		}
	}
	const onRadioPause = (id) => {
		const audioNode = audioNodeList.value[`audioNode-${id}`]
		audioNode && !audioNode.paused && audioNode.pause()
		if (id === musicData.value.id) {
			musicData.value = {
				id: null,
				index: null,
				url: null
			}
		}
	}
	const onRadioDownload = (data) => {
		const name = data.sound.substring(data.sound.lastIndexOf('/') + 1)
		downloadUtil.fileDownLoad(data.sound, name)
	}
	const visible = ref({})
	const speed = ref(1)
	const speedOptions = [
		{ label: '0.25', value: 0.25 },
		{ label: '0.5', value: 0.5 },
		{ label: '0.75', value: 0.75 },
		{ label: '正常', value: 1 },
		{ label: '1.25', value: 1.25 },
		{ label: '1.5', value: 1.5 },
		{ label: '1.75', value: 1.75 },
		{ label: '2', value: 2 }
	]
	const onPlayPopoverHide = (id) => {
		console.log('hide', id)
		onRadioPause(id)
	}
	const onPlayPopoverClose = (id) => {
		visible.value[id] = false
	}
	const onPlaySpeedChange = (value) => {
		const audioNode = audioNodeList.value[`audioNode-${musicData.value.id}`]
		audioNode.playbackRate = value
	}

	/**
	 * 筛选
	 */
	const searchType = ref(0)
	const searchText = ref('')
	const searchOption = ref({
		customerName: undefined,
		contactPhone: undefined,
		data: '1',
		tempPersonIds: [],
		personIds: []
	})
	/**
	 * ====================
	 *     自定义部门逻辑
	 * ====================
	 */
	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref(store.authDeptList)
	const onPersonChange = (value, label, extra) => {
		searchOption.value.personIds = tool.getAllBottomPersonIds(extra.allCheckedNodes)
		// table.value.refresh(true)
	}

	/**
	 * 更多筛选条件逻辑
	 */
	const screenVisible = ref(false)
	const labelCol = { style: { width: '100px' } }

	// 更多筛选条件初始值
	const moreDefaultSearch = {
		recordFlag: '',
		communicationType: '',
		transTime: null,
		callMinNum: null,
		callMaxNum: null
	}
	const moreSearch = ref({ ...moreDefaultSearch })
	const clearSearch = () => {
		moreSearch.value = { ...moreDefaultSearch }
	}
	const doMoreSearch = () => {
		const { callMinNum, callMaxNum } = moreSearch.value
		if (callMinNum && callMaxNum && callMinNum > callMaxNum) {
			return message.warning('最小时长不能大于最大时长')
		}

		screenVisible.value = false
		table.value.refresh(true)
	}
	const cancelMoreSearch = () => {
		screenVisible.value = false
	}
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)

	const dataChange = (value) => {
		nextTick(() => {
			if (value !== '5') {
				onCustomClick()
			}
		})
	}
	const onCustomClick = () => {
		searchOption.value.tempPersonIds = []
		searchOption.value.personIds = []
	}

	/**
	 * 公共查询参数
	 */
	const getParams = (parameter = {}) => {
		if (searchType.value === 0) {
			searchOption.value.customerName = searchText.value
			searchOption.value.contactPhone = null
		} else if (searchType.value === 1) {
			searchOption.value.customerName = null
			searchOption.value.contactPhone = searchText.value
		}

		const { id } = tool.data.get('USER_INFO')
		const params = {
			...searchOption.value,
			...moreSearch.value,
			...parameter,
			tenantId: tool.data.get('loginData').tenantId,
			userId: id
		}
		if (params.transTime) {
			params.stime = params.transTime[0]
			params.etime = params.transTime[1]
			delete params.transTime
		}
		if (params.data === '5') {
			params.datastr = params.personIds.join(',')
		}
		delete params.tempPersonIds
		delete params.personIds

		return params
	}

	/**
	 * 获取合同列表数据
	 */
	const loadData = (parameter) => {
		// audioNode.value && onRadioPause()
		const params = getParams(parameter)
		return callRecordApi.getList(params).then((res) => {
			visible.value = res.records.reduce((total, item) => ({ ...total, [item.id]: false }), [])
			return res
		})
	}

	/**
	 * 导出合同
	 */
	const loading = ref(false)
	const onExportContract = () => {
		loading.value = true
		const params = getParams()
		callRecordApi
			.exportList(params)
			.then((res) => {
				downloadUtil.resultDownload(res)
			})
			.finally(() => {
				loading.value = false
			})
	}
</script>
<style lang="less" scoped>
	:deep(.ant-table-thead > tr > th::before) {
		width: 0 !important;
	}
	.center {
		text-align: center;
	}
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 350px);
	// }
	.audio {
		font-size: 20px;
		cursor: pointer;
	}
	.audio.active {
		color: #409eff;
	}
</style>
